package com.apestech.framework.run.core;

import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.StringFuncUtil;

import java.util.ArrayList;

/**
 * 数据对照解析
 *
 * @author hup
 * @create 2018-03-15-17:54
 */
public class DataMapper extends StringFuncUtil{

    private ArrayList<String> list=new ArrayList<String>();
    private int size=-1;
    private JSONObject result=null;
    private JSONObject inParam;

    public DataMapper(String input, JSONObject inParam){
        this.inParam=inParam;
        if(input!=null){
            input=input+";";
            String[] plist=input.split(";");
            int len=plist.length;
            for(int i=0; i<len; i++){
                if(plist[i]!=""){
                    list.add(plist[i]);
                }
            }
        }
        this.size=list.size();
    }

    public DataMapper(ArrayList<String> list, JSONObject inParam){
        this.inParam=inParam;
        this.list=list;
        this.size=list.size();
    }

    public void expain() throws Exception {
        result=null;
        if(size>0){
            result=new JSONObject();
        }
        for(int i=0; i<size; i++){
            String s=list.get(i);
            String key="";
            String value="";
            if(s.indexOf("=")>0){
                value=s.substring(s.indexOf("=")+1,s.length());
                key=s.substring(0, s.indexOf("="));
            } else {
                key=s;
                value=s;
            }
            if(isExpress(value)){
                Object v=this.doExpression(value, this.inParam);
                this.result.put(key,v);
            } else {
                this.result.put(key, this.inParam.get(value));
            }
        }
    }

    private boolean isExpress(String text){
        if(text==null){
            return false;
        }
        String s=text.toUpperCase();
        if(text.indexOf("+")>0) return true;
        if(text.indexOf("-")>=0) return true;
        if(text.indexOf("*")>0) return true;
        if(text.indexOf("/")>0) return true;
        if(text.indexOf(" AND ")>0) return true;
        if(text.indexOf(" OR ")>0) return true;
        if(text.indexOf(" IF ")>=0) return true;
        if(text.indexOf(" WHILE ")>=0) return true;
        return false;
    }

    public JSONObject getResult(){
        return this.result;
    }

}
